package org.example.client.veri.bind;

import lombok.extern.slf4j.Slf4j;
import org.example.common.RpcRequest;
import org.example.common.RpcResponse;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;

/**
 * @author mojito
 * @Classname Client
 * @Description TODO
 * @Date 2020/7/20 下午9:46
 **/
@Slf4j
public class RpcProxyClient implements Client {
    private String host;
    private int port;

    public RpcProxyClient(String host, int port) {
        this.host = host;
        this.port = port;
    }

    public <T> T getService(Class<T> clazz) {
        ServiceProxyFactory<T> proxyFactory = new ServiceProxyFactory<>(clazz);
        return proxyFactory.newInstance(this);
    }

    @Override
    public RpcResponse process(RpcRequest rpcRequest) {
        Socket socket = null;
        ObjectOutputStream outputStream = null;
        ObjectInputStream inputStream = null;
        Object object = null;
        try {
            socket = new Socket(host, port);
            outputStream = new ObjectOutputStream(socket.getOutputStream());
            outputStream.writeObject(rpcRequest);
            outputStream.flush();
            inputStream = new ObjectInputStream(socket.getInputStream());
            object = inputStream.readObject();
        } catch (Exception e) {
            log.error("rpc call error:{}", e.getMessage());
        } finally {
            try {
                outputStream.close();
                inputStream.close();
                socket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return (RpcResponse) object;
    }
}
